//
//  BCaseRealm.swift
//  MySwiftObject
//
//  Created by anscen on 2022/6/1.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
fileprivate let base = BaseRealm()
class BShelfRealm: NSObject {
    //MARK:判断是否有数据
    public static func haveData(_ bookId :String) -> Bool{
        guard let realm = base.realm else {
            return false
        }
        let some = realm.objects(GKBook.self).filter("bookId == '\(bookId)'")
        return some.count > 0 ? true : false
    }
    //MARK:有就更新没有就增加
    public static func insertData(_ book :GKBook){
        guard let realm = base.realm else {
            return
        }
        let haveData = haveData(book.bookId ?? "")
        guard let _ = try? realm.write({
            if haveData{
                realm.add(book, update: .all)
            }else{
                realm.add(book)
            }
        }) else { return }
    }
    //MARK:获取某一个数据
    public static func getData(_ bookId :String) ->GKBook?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(GKBook.self).filter("bookId == '\(bookId)'")//.sorted(by: "user.userId", ascending: true)
        return some.first
    }
    //MARK:获取所有数据
    public static func getDatas() ->[GKBook]?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(GKBook.self)
        return some.reversed()
    }
    //MARK:删除指定数据
    public static func deleteData(_ bookId :String){
        guard let realm = base.realm else {
            return
        }
        if let user = getData(bookId){
            try? realm.write({
                realm.delete(user)
            })
        }
    }
    //MARK:删除所有数据
    public static func deleteAll(){
        guard let realm = base.realm else {
            return
        }
        try? realm.write({
            realm.deleteAll()
        })
    }
}
